package architecture;

import java.io.*;

//InstructionMemory
public class InstructionMemory{
	private char memory[]=new char[1024];

	MyInt read_address;
	MyInt instruction;
	MyInt rs;
	MyInt rt;
	//MyInt instr_31_26;//OpCode
	MyInt opCode;//OpCode
	//MyInt instr_5_0;//FuncCode
	
	void initMem(String filename) throws Exception{
		RandomAccessFile ra=new RandomAccessFile(filename,"r");
		int value;
		int address=0;
		try{
			while(true){
				value=ra.readByte();
				putByte(address++,ra.readByte());
			}	
		}catch(EOFException e){}
	}
	
	int getWord (int address) {
		if ((address < 0) || (address > 1020)) {
			System.out.println("invalid address in DataMemory!");
		}
		return
			(memory[address] << 24) +
			((memory[address+1] << 16) & 0xff0000) +
			((memory[address+2] << 8) & 0xff00) +
			((memory[address+3]) & 0xff);
	}
	void putByte( int address, int value )
	{
		if ((address < 0) || (address > 1020)) {
			System.out.println("invalid address in DataMemory!");
		}
		memory[address] = (char)(value);
	}
	int getByte (int address) {
		int n ;
		if ((address < 0) || (address > 1023)) {
			System.out.println("invalid address in DataMemory!");
		}
		n = (int)memory[address] ;
		return n ;
	}
	void putWord (int address, int value) {
		if ((address < 0) || (address > 1020)) {
			System.out.println("invalid address in DataMemory!");
		}
		memory[address] = (char)(value >> 24);
		memory[address+1] = (char)((value & 0xff0000) >> 16);
		memory[address+2] = (char)((value & 0xff00) >> 8);
		memory[address+3] = (char)(value & 0xff);
	}
	void clockEvent(){
		instruction.i=getWord(read_address.i);
		opCode.i=MyUtil.bitsofint(instruction.i,31,26);
		rs.i=MyUtil.bitsofint(instruction.i,25,21);
		rt.i=MyUtil.bitsofint(instruction.i,20,16);
	}
	void dump(){
		System.out.println("--------");
		System.out.println("InstructionMemory:");
		System.out.println("read_address:"+read_address);
		System.out.println("instruction:"+instruction);
		System.out.println("rs:"+rs);
		System.out.println("rt:"+rt);
		System.out.println("opCode:"+opCode);
		System.out.println("--------");
	}
}